"""
This file is part of GSBEdit. For copyright and licensing information, please
see gsbedit.py in the GSBEdit base directory.
"""


import wx
import os.path

import game_data.module as gdm
import ui_elements.controls.module_tree as mt
import ui_elements.module_editor as me
import ui_elements.module_wizard as mw
import app.module_config as mc


class ModuleManager(wx.Panel):
    def __init__(self, parent, parent_window, gsbi):
        wx.Panel.__init__(self, parent, -1)
        
        self.parent = parent
        self.gsbi = gsbi
        self.parent_window = parent_window
        
        self.editor = me.ModuleEditor(self)
        
        self.content = wx.BoxSizer(wx.HORIZONTAL)
        self.mt = mt.ModuleTree(self, gsbi, self.select_callback, self.double_select_callback)
        self.content.Add(self.mt, 3, wx.EXPAND)
        self.content.Add(self.editor, 4, wx.EXPAND)
        self.SetSizer(self.content)

    
    def double_select_callback(self, mod, module):
        #me.ModuleEditorWindow(self.parent_window, module)
        pass


    def select_callback(self, mod, module):
        if module == None:
            self.editor.set_module(None)
            return
    
        self.editor.set_module(module)
        self.current_mod = mod
        self.current_module = module
    
    
    def new_gsbi(self, gsbi):
        self.gsbi = gsbi
        self.mt.new_gsbi(gsbi)

    
    def add_module(self):
        mw.ModuleWizardWindow(self)
    
    
    def create_module(self, name, class_name):
        internal_name = name.lower().replace(' ', '_')
        mod = self.gsbi.get_current_mod()
        module_filename = os.path.join(mod.modules_dir, internal_name + '.txt')
        
        module = gdm.Module(module_filename)
        configs = mc.ModuleConfig('data/modules.cfg')
        
        module.set_value('config', 'name', internal_name)
        module.set_value('config', 'guiname', name)
        module.load_template(class_name, configs.get_config(class_name))
        module.write_to_file()
        
        mod.reload_module_list()
        
        self.refresh_tree()
        self.force_select_module(module)
    
    
    def refresh_tree(self):
        self.mt.refresh_tree()
    
    
    def force_select_module(self, module):
        leaf = self.mt.get_leaf_from_module(module)
        self.mt.expand_parents(leaf)
        self.mt.select_item(leaf)


    def delete_module(self):
        confirm_dlg = wx.MessageDialog(self, 'Are you sure you wish to delete this module?', 'Confirm delete', style=wx.YES_NO | wx.CENTRE | wx.ICON_QUESTION)
        result = confirm_dlg.ShowModal()
        if result == wx.ID_YES:
            self.current_module.delete()
            self.current_mod.reload_module_list()
            self.refresh_tree()
            return True
        return False
    
    
    def closing(self):
        self.editor.closing()
            
